const express = require('express');
const router = express.Router();
const Type = require('../models/type');
const {Op} = require("sequelize");
const Goods = require('../models/goods');
const UserAction = require('../models/user_action');
const History = require('../models/history');
const RelatedFigures = require('../models/related_figures');
const RelatedEvents = require('../models/related_events');
const GoodsTag = require('../models/goods_tag');
const sequelize = require('../config/db');

// 获取所有类型列表
router.get('/list', async (req, res) => {
    try {
        const types = await Type.findAll(); // 使用Sequelize的findAll方法获取所有类型
        res.send({
            code: 200,
            data: types
        });
    }catch (error) {
        console.error('获取类型列表失败:', error);
        res.send({code:500, message: error.message });
    }
})


router.delete('/delete', async (req, res) => {
    const session = req.neo4j.session();
    try{
        const {id} = req.body;
        const type = await Type.findByPk(id);
        if(!type){
            return res.send({code: 500, message: '数据不存在!'});
        }
        
        // 查找该类型关联的所有商品
        const relatedGoods = await Goods.findAll({
            where: { type: id },
            include: [
                { model: History, as: 'history' }
            ]
        });
        
        // 获取所有商品ID和历史记录ID
        const goodsIds = relatedGoods.map(good => good.id);
        const historyIds = relatedGoods
            .filter(good => good.history)
            .map(good => good.history.id);
        
        if(goodsIds.length > 0) {
            // 1. 删除goods_imgs表数据 (手动执行SQL，因为可能没有Model定义)
            await sequelize.query(
                `DELETE FROM goods_imgs WHERE goods_id IN (?)`,
                {
                    replacements: [goodsIds],
                    type: sequelize.QueryTypes.DELETE
                }
            );
            
            // 2. 删除goods_tag关联表数据
            await GoodsTag.destroy({
                where: {
                    goods_id: {
                        [Op.in]: goodsIds
                    }
                }
            });
            
            // 3. 删除所有关联的历史人物和事件
            await RelatedFigures.destroy({
                where: {
                    goods_id: {
                        [Op.in]: goodsIds
                    }
                }
            });
            
            await RelatedEvents.destroy({
                where: {
                    goods_id: {
                        [Op.in]: goodsIds
                    }
                }
            });
            
            // 4. 删除所有关联商品的用户行为记录
            await UserAction.destroy({
                where: {
                    goods_id: {
                        [Op.in]: goodsIds
                    }
                }
            });
            
            // 5. 删除所有关联商品
            await Goods.destroy({
                where: {
                    id: {
                        [Op.in]: goodsIds
                    }
                }
            });
            
            // 6. 删除历史记录
            if(historyIds.length > 0) {
                await History.destroy({
                    where: {
                        id: {
                            [Op.in]: historyIds
                        }
                    }
                });
            }
            
            // 7. 删除Neo4j中的关联节点和关系
            await session.run(`
                MATCH (t:Type {id: $typeId})
                OPTIONAL MATCH (g:Goods)-[r1:BELONGS_TO]->(t)
                OPTIONAL MATCH (g)-[r2]-()
                OPTIONAL MATCH ()-[r3]->(g)
                DELETE r1, r2, r3, g, t
            `, { typeId: id });
            
            // 清理没有关系的节点
            await session.run(`
                MATCH (n)
                WHERE NOT (n)--() AND NOT n:User
                DELETE n
            `);
        } else {
            // 如果没有关联商品，只删除类型节点
            await session.run(`
                MATCH (t:Type {id: $typeId})
                DELETE t
            `, { typeId: id });
        }
        
        // 最后删除类型本身
        await type.destroy();
        
        res.send({code: 200, message: '删除成功!'});
    }catch(error){
        console.error('删除分类失败:', error);
        res.send({code:500, message: error.message });
    } finally {
        await session.close();
    }
})

router.post('/post', async (req, res) => {
    try{
        const {name, id, cover} = req.body;
        const type = await Type.findByPk(id);
        if(!type){
            const result = await Type.create({name, cover})
            res.send({data: result, code: 200, message: '添加成功！'});
        }else{
            type.name = name;
            type.cover = cover;
            await type.save();
            res.send({code: 200, message: '修改成功！'});
        }
    }catch (error) {
        res.send({code:500, message: error.message });
    }
})

router.get('/page', async (req, res) => {
    console.log('page')
    try {
        const {page = 1, pageSize = 10, name = ''} = req.query;
        const offset = (page - 1) * pageSize;
        const where = {};
        if (name && name.trim().length > 0){
            where.name = {
                [Op.like]: `%${name.trim()}%`
            }
        }
        const {count, rows} = await Type.findAndCountAll({
            where,
            offset: parseInt(offset),
            limit: parseInt(pageSize),
            order: [['id', 'ASC']]}
        );
        res.send({
            code: 200,
            data: rows,
            total: count
        })
    }catch (error) {
        res.send({code:500, message: error.message });
    }
})

//获取某个类型的详情
router.get('/:id', async (req, res) => {
    try {
        const typeId = req.params.id; // 获取URL中的类型ID
        const type = await Type.findByPk(typeId);
        res.send({code:200, data:type});
    } catch (error) {
        console.error('获取类型详情失败:', error); // 打印错误信息到控制台
        res.send({code:500, message: error.message }); // 返回500状态码和错误信息
    }
})


module.exports = router
